package com.noahedu.style.span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.text.style.ReplacementSpan;
import android.util.Log;

/**
 * 这个类的作用是在文本上方添加注解，标记，拼音等内容
 * 
 * 
 */
 class NoteSpan extends ReplacementSpan{	
	
	private String mNote;
	private float mTextOffset;
	private float mNoteOffset;
	private int mPadding;  // left and right padding
	
	public NoteSpan(String note) {
		this(note, -1);
	}
	
	public NoteSpan(String note, int padding) {
		mNote = note;
		mPadding = padding;
		mTextOffset = mNoteOffset = 0;
	}

	@Override
	public void draw(Canvas canvas, CharSequence text, int start, int end,
			float x, int top, int y, int bottom, Paint paint) {
		canvas.drawText(mNote, x+mNoteOffset, y-paint.getFontSpacing(), paint);
		canvas.drawText(text, start, end, x+mTextOffset, y, paint);
	}

	@Override
	public int getSize(Paint paint, CharSequence text, int start, int end,
			FontMetricsInt fm) {
		
		float [] textw = new float[end-start]; 
		paint.getTextWidths(text, start, end, textw);
		
		float [] pinyinw = new float[mNote.length()];
		paint.getTextWidths(mNote, 0, mNote.length(), pinyinw);
		
		float tw = 0f;
		float pw = 0f;
		for(float i : textw) {
			tw += i;
		}
		for(float j : pinyinw) {
			pw += j;
		}
		
		float padding = 0;
		if(mPadding == -1) {
			padding = paint.getTextSize() / 8;
		} else {
			padding = mPadding;
		}
		
		int w = (int) Math.ceil(Math.max(tw, pw) + 2 * padding) ;
		mTextOffset = (w - tw) / 2;
		mNoteOffset = (w - pw) / 2;		

        if (fm != null) {
            fm.ascent = -(int)paint.getFontSpacing()*2; 
            fm.descent = 0; 

            fm.top = fm.ascent;
            fm.bottom = 0;
        }

        return w;
	}
}
